<template>
    <div class="WeChat_bangd">
        <div class="head_title">
            <h2>猪爸爸账号微信绑定</h2>
            <p>开发者将猪爸爸账号与微信公众号绑定后，您将能通过微信账号登录猪爸爸所有平台并能在公众号收到及时的消息推送。</p>
        </div>
        <el-form :model="dynamicValidateForm" :rules="rules" ref="dynamicValidateForm" class="demo-dynamic">
            <el-form-item prop="phone">
                <el-input placeholder="请输入您的邮箱地址或手机号" v-model="dynamicValidateForm.phone"></el-input>
            </el-form-item>
            <el-form-item prop="password" v-if="WeChat_bangd">
                <el-input placeholder="请输入密码" type="password" v-model="dynamicValidateForm.password"></el-input>
            </el-form-item>
            <el-form-item class="yzm" prop="yzm" v-if="!WeChat_bangd">
                <el-input placeholder="请输入验证码" v-model="dynamicValidateForm.yzm" class="input-with-select"></el-input>
                <div class="box">
                    <a v-if="isYZMShow" href="javascript:;" class="btn-get-code" @click="getYZM">获取短信验证码</a>
                    <div v-else class="timer">
                    {{ time }} s
                    </div>
                </div>
            </el-form-item>
            <el-form-item class="bot_btn">
                <el-button type="primary" @click="submitForm('dynamicValidateForm')">登录</el-button>
                <span class="span_text" v-if="phoneVerification" @click="switchBtn">使用手机验证码登录</span>
                <span class="span_text" v-if="paswdVerification" @click="paswdBtn2">使用密码登录</span>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
export default {
    data (){
        var validatephone = (rule, value, callback) => {
		    if (!value) {
		      return callback(new Error('手机号不能为空'));
		    }
		    if(!(/^1[3456789]\d{9}$/.test(value))){
		      return callback(new Error('手机号格式不正确!'));
		    }
		    callback();
		  };
		  var validateyzm = (rule, value, callback) => {
		    if (!value) {
		      return callback(new Error('验证码不能为空'));
		    }
		    
		    callback();
		  };
		  var validateemail = (rule, value, callback) => {
		   
		    if (!value) {
		      return callback(new Error('邮箱不能为空！'));
		    }
		    if(!(/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value))){
		      return callback(new Error('邮箱格式不正确!'));
		    }
		    callback();
		  };
		  var validatepass = (rule, value, callback) => {
		    
		    if (!value) {
		      return callback(new Error('密码不能为空'));
		    }
		    
		    callback();
		  };
        return {
            WeChat_bangd:true,
            phoneVerification:true,
            paswdVerification:false,
            isYZMShow:true,
            time:60,
            rules: {
              phone: [
                { validator: validatephone, trigger: 'blur' }
              ],
              yzm: [
                { validator: validateyzm, trigger: 'blur' }
              ],
              email: [
                { validator: validateemail, trigger: 'blur' }
              ],
              password: [
                { validator: validatepass, trigger: 'blur' }
              ],
            },
            dynamicValidateForm: {
                password:'',
                phone: '',
                yzm:''
            },
            loginType:0,
            code:'',
            openId:'',
        }
    },

    methods:{
        getUrlKey(name){
            //获取url 参数
            return decodeURIComponent((new RegExp('[?|&]'+name+'='+'([^&;]+?)(&|#|;|$)').exec(location.href)||[,""])[1].replace(/\+/g,'%20'))||null;
        },
        getCodeApi(state){//获取code
            //let urlNow=encodeURIComponent(window.location.href);
            let urlNow=encodeURIComponent('https://www.zhubaba.cn/#/weChatbangd');
            let scope='snsapi_base';    //snsapi_userinfo   //静默授权 用户无感知
            let appid='wx977fa0e436559077';
            let url=`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${urlNow}&response_type=code&scope=${scope}&state=${state}&connect_redirect=1#wechat_redirect`;
            window.location.replace(url);
        },
        //使用验证码登录
        switchBtn(){
            console.log('vvv')
            this.WeChat_bangd = !this.WeChat_bangd
            this.phoneVerification = false;
            this.paswdVerification = true;
            this.loginType = 1;
        },
        //使用密码登录
        paswdBtn2(){
            this.WeChat_bangd = !this.WeChat_bangd
            this.phoneVerification = true;
            this.paswdVerification = false;
            this.loginType = 0;
        },
        //登录绑定
         submitForm(formName) {
            this.$refs[formName].validate((valid) => {
            if (valid) {
                // alert('submit!');
                this.$ajax.post('/weiChatCommon/band',{
                  mobile:this.dynamicValidateForm.phone,
                  pwd:this.dynamicValidateForm.password,
                  verifyCode:this.loginType==1 ? this.dynamicValidateForm.yzm : null,
                  loginType:this.loginType,
                    openId:this.openId
                }).then(res =>{
                  console.log(res,'成功！');
                  if(res.data.code == 0){
                    this.$message({
                      type:'success',
                      message:'绑定成功'
                    })
                    setTimeout(() => {
                      this.$router.push('/bindingSuccess')
                    },1000)
                    
                  }else if(res.data.code == 204){
                    this.$message({
                      type:'error',
                      message:res.msg
                    })
                  }else if(res.data.code == 202){
                    this.$message({
                      type:'error',
                      message:res.msg
                    })
                  }else{
                      this.$message({
                          type:'error',
                          message:res.msg
                      })
                  }
                }).catch(err =>{
                  console.log(err)
                })
            } else {
                console.log('error submit!!');
                return false;
            }
            });
        },
        //获取验证码
        getYZM(){
		    if(this.dynamicValidateForm.phone == "" ){
		      this.$message.error('手机号不能为空!');
		      return ;
		    }
		    if(!(/^1[3456789]\d{9}$/.test(this.dynamicValidateForm.phone))){
		      this.$message.error('手机格式不正确!');
		      return ;
		    }
		    this.postYZM(); // 向后台请求数据
		    this.isYZMShow = !this.isYZMShow;
		    let i = 60;
		    var timer = setInterval(()=>{
		      i -- ;
		      if(i == 0){
		        this.isYZMShow = !this.isYZMShow;
		        clearInterval(timer);
		        i = 60;
		      }else{
		        this.time = i;
		      }
		      
		    },1000)
          },
          //向后端发送获取验证码请求
          postYZM(){
		    this.$ajax.post("/user/sendMobileCode",{
		        type:1,
		        mobile:this.dynamicValidateForm.phone
		      },)
		      .then((res)=>{
		        if(res.data.code == 0){
		          this.$message({
		            message: '验证码发送成功!',
		            type: 'success'
		          });
		        }else {
                    this.$message.error(res.data.msg)
                }
		      })
		  },
    },
    mounted(){
        document.title = this.$route.meta.title;
        this.code = this.getUrlKey("code");
            if(this.code==null){
                this.getCodeApi('456');
            }else{
                this.$ajax.post('/weiChatCommon/checkBand',{"code":this.code}).then(res=>{
                    console.log(res)
                    if(res.data.code==0){
                        this.$router.replace('/bindingSuccess');
                    }else if (res.data.code==209){
                        this.openId=res.data.data;
                    }else {
                        this.$message({
                            type:'error',
                            message:res.msg
                        })
                    }
                })
            }
    },
}
</script>
<style lang="scss" >
    .WeChat_bangd{
        .el-form{
            width: 80%;
            .el-input__inner{
                border-top-width: 0px;
                border-left-width: 0px;
                border-right-width: 0px;
                border-bottom-width: 1px;
                padding: 0;
                border-radius: 0;
            }
            .el-form-item.bot_btn{
                .el-form-item__content{
                    margin-top: 20px;
                    .el-button{
                        width: 100%;
                    }
                    .el-button--primary{
                        background-color: #4DBA9B;
                        border-color: #4DBA9B;
                    }
                    .span_text{
                        color: #4DBA9B;
                        display: inline-block;
                        line-height: 18px;
                    }
                }
                
            }
            .yzm .box a{
                background-color:#4DBA9B;
                margin-right: 0;
            }
            
        }
        .head_title{
            width: 80%;
            margin: 0 auto;
            padding-top: 50px;
            h2{
                color: #4DBA9B;
                margin-bottom: 15px;
            }
            p{
                color: #999;
                margin-bottom: 30px;
                line-height: 18px;
            }
        }
    }
</style>